package com.xyh.concurrency.example.count;

import com.xyh.concurrency.annoations.NotThreadSafe;
import com.xyh.concurrency.annoations.Recommend;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 高并发原子性包
 * Atomic 包下面的所有类 cas
 */
@Slf4j
@Recommend
public class CountExample2 {
    //创建初始化新线程
    private static int clientTotal = 5000;
    //允许并发的线程数
    private static int threadTotal = 200;
    /**
     * 原子性表示线程
     */
    private static AtomicInteger count = new AtomicInteger(0);

    public static void main(String[] args) throws InterruptedException {
        //创建线程池
        ExecutorService executorService = Executors.newCachedThreadPool();
        //创建并发允许额数量
        final Semaphore semaphore = new Semaphore(threadTotal);
        //最大线程数
        CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i < clientTotal; i++) {
            executorService.execute(() -> {
                try {
                    //开启线程阻塞
                    semaphore.acquire();
                    add();
                    //关闭线程阻塞,释放后钱200 线程
                    semaphore.release();
                } catch (Exception ex) {
                    log.error("name", ex.toString());
                }
                countDownLatch.countDown();
            });

        }

        countDownLatch.await();
        executorService.shutdown();
        log.info("cpunt:{}", count.get());

    }

    public static void add() {
        //线程不安全
        //前++ 后++
        count.incrementAndGet();
        //count.getAndAccumulate();
    }
}
